package top.choviwu.garbage.sort.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import top.choviwu.garbage.sort.constant.GsCode;
import top.choviwu.garbage.sort.entity.GsInfo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class JsoupUtils {

    public static final String URL = "https://laji.lr3800.com/api.php?name=";

    public static final String SO_JSON = "https://www.sojson.com/auth_v_1_0/trash/complete.shtml";


    public static GsInfo[] getGsList(String keyWords){
        List<GsInfo> list = CollUtil.newArrayList();
        try {
//            垃圾分类，0 为可回收、1 为有害、2 为厨余(湿)、3 为其他(干)
            HttpResponse response = HttpUtil.createGet(URL+ URLEncoder.encode(keyWords,"utf-8")).execute();
            if(response.isOk()){
                String body = response.body();
                JSONObject jsonObject = JSONUtil.parseObj(body);
                if(jsonObject.getInt("code")== HttpStatus.HTTP_OK){
                    JSONArray array = jsonObject.getJSONArray("newslist");
                    if(array.size()>0){
                        for (int i = 0; i < array.size(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            for (GsCode gsCode: GsCode.values()){
                                if(object.getInt("type").intValue()==gsCode.getType()){
                                    GsInfo info = new GsInfo();
                                    info.setName(object.getStr("name")).setType(gsCode);
                                    list.add(info);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        GsInfo[] gsCodes = new GsInfo[list.size()];

        return list.toArray(gsCodes);
    }

}
